package com.yq.testmodule.barrage

import android.content.Context
import android.os.Handler
import android.os.Looper
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager2
import androidx.recyclerview.widget.RecyclerView
import com.fmt.mvi.learn.gobal.log
import com.yq.testmodule.R
import net.lucode.hackware.magicindicator.buildins.UIUtil

/**
 * 垂直滚动弹幕：不需要处理新增数据，只展示默认数据，可设置循环播放
 */
class VerticalBarrageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : RecyclerView(context, attrs) {


    var mAdapter: Adapter<*>? = null
    override fun setAdapter(adapter: Adapter<*>?) {
        super.setAdapter(adapter)
        mAdapter = adapter
    }

    //真实弹幕数据
    val barrageData = arrayListOf<String>()

    //展示的弹幕数据
    val showData = arrayListOf<String>()

    val mHandler = Handler(Looper.getMainLooper())
    val mRunnable = MyRunnable()

    var currentIndex = 0

    val delayTime = 2000L

    inner class MyRunnable : Runnable {
        override fun run() {
            //取数据，如果取完后，从头开始
            if (currentIndex >= barrageData.size) {
                currentIndex = 0
            }
            val data = barrageData[currentIndex]
            showData.add(data)
            currentIndex++
            mAdapter?.notifyItemInserted(mAdapter!!.itemCount - 1)
            smoothScrollToPosition(mAdapter!!.itemCount - 1)
            mHandler.postDelayed(mRunnable, delayTime)
        }
    }

    val maxItem = 4

    init {
        //实现默认从底部出数据效果
        for (i in 0 until maxItem) {
            showData.add("")
        }
        layoutManager = SmoothScrollLayoutManager(
            context,
            VERTICAL,
            false
        )
        mAdapter = MAdapter()
        adapter = mAdapter

        addOnScrollListener(object : OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                //计算第一个可见条目划出屏幕的百分百，第二个item 停留时透明度50% 向上滚动变为0， 第三个item，从第三个滚动至第二个时透明度变为50%透明度
                val layoutManager = layoutManager as LinearLayoutManager2
                val firstVisiblePosition = layoutManager.findFirstVisibleItemPosition()
                val itemView = layoutManager.findViewByPosition(firstVisiblePosition)
                //第一个条目离开百分比
                val fistLeavePer = Math.abs(itemView!!.y) / itemView!!.height

                val itemView2 = layoutManager.findViewByPosition(firstVisiblePosition + 1)
                itemView2?.alpha = 0.5f - fistLeavePer * .5f

                val itemView3 = layoutManager.findViewByPosition(firstVisiblePosition + 2)
                itemView3?.alpha = 1 - fistLeavePer * .5f


                ("第一个条目离开百分比： ${fistLeavePer} " +
                 "第二个条目透明度： ${itemView2?.alpha} " +
                 "第三个条目透明度： ${itemView3?.alpha}").log()

                "=============".log()
            }
        })

    }

    fun initData(data: List<String>) {
        barrageData.clear()
        barrageData.addAll(data)

        //设置rv高度
        layoutParams.height = UIUtil.dip2px(context, 60.0) * maxItem
    }

    fun startScroller() {
        mHandler.postDelayed(mRunnable, delayTime) // 1000 毫秒表示 1 秒
    }


    fun destory() {
        mHandler.removeCallbacks(mRunnable)
    }


    inner class MAdapter : Adapter<ViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            return MyViewHolder(
                LayoutInflater.from(parent.context).inflate(R.layout.item_test, null)
            )
        }

        inner class MyViewHolder(itemView: View) : ViewHolder(itemView) {

        }

        override fun getItemCount(): Int {
            return showData.size
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val itemView = holder.itemView
            if (showData[position].isEmpty()) {
                itemView.visibility = GONE
            } else {
                itemView.visibility = VISIBLE
                itemView.alpha = 1f
            }
            holder.itemView.findViewById<TextView>(R.id.tv).text = showData[position]
        }

    }
}